package com.bpmn.flow.listener;

import com.bpmn.common.enums.BusinessStatusEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.delegate.event.FlowableProcessStartedEvent;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 监听 {@link ProcessInstance} 的状态变更，更新其对应的 status 状态
 *
 * @author rain
 */
@Component
@Slf4j
public class BpmProcessInstanceEventListener extends AbstractFlowableEngineEventListener {

    public static final Set<FlowableEngineEventType> PROCESS_INSTANCE_EVENTS = Set.of(
            FlowableEngineEventType.PROCESS_CREATED, FlowableEngineEventType.PROCESS_STARTED, FlowableEngineEventType.PROCESS_COMPLETED);

    @Resource
    @Lazy // 解决循环依赖
    private RuntimeService runtimeService;

    public BpmProcessInstanceEventListener() {
        super(PROCESS_INSTANCE_EVENTS);
    }

    @Override
    protected void processCreated(FlowableEngineEntityEvent event) {
        ProcessInstance instance = (ProcessInstance) event.getEntity();
        log.info("流程实例【{}】创建", instance.getProcessInstanceId());
        runtimeService.updateBusinessStatus(instance.getProcessInstanceId(), BusinessStatusEnum.DRAFT.getStatus());
    }

    @Override
    protected void processStarted(FlowableProcessStartedEvent event) {
        ProcessInstance instance = (ProcessInstance) event.getEntity();
        log.info("流程实例【{}】开始", instance.getProcessInstanceId());
        runtimeService.updateBusinessStatus(instance.getProcessInstanceId(), BusinessStatusEnum.WAITING.getStatus());
    }

    @Override
    protected void processCompleted(FlowableEngineEntityEvent event) {
        ProcessInstance instance = (ProcessInstance) event.getEntity();
        log.info("流程实例【{}】已完成", instance.getProcessInstanceId());
        runtimeService.updateBusinessStatus(instance.getProcessInstanceId(), BusinessStatusEnum.FINISH.getStatus());
    }

}
